package com.shr.lease.web.admin.custom.interceptor;

import com.shr.lease.common.context.LoginUser;
import com.shr.lease.common.context.LoginUserContext;
import com.shr.lease.common.exception.LeaseException;
import com.shr.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import static com.shr.lease.common.utils.JWTUtil.*;

/**
 * @author Haoran Sun
 * @since 2024/06/22
 */

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("access_token");

        if (StringUtils.isBlank(token)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }else {
            Claims claims = parseToken(token);
            LoginUserContext.setLoginUser(
                    LoginUser.builder()
                            .userId(claims.get("userId", Long.class))
                            .username(claims.get("username", String.class))
                            .build()
            );
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.removeLoginUser();
    }
}
